const wechat = require("co-wechat");
const defaultOptions = {
  module: "wechat",
  controller: "dev"
};
module.exports = (options, app) => {
  options = Object.assign({}, defaultOptions, options);
  return wechat(options).middleware(async (message, ctx) => {
    console.log(message);
    const isMultiModule = app.modules.length;
    let Controller;
    if (isMultiModule) {
      //多模块应用
      const Module = app.controllers[options.module];
      if (!Module) return `模块${options.module}未定义`;
      else {
        Controller = Module[options.controller];
        if (!Controller) return `controller${options.controller}未定义`;
      }
    } else {
      //单模块
      Controller = app.controllers[options.controller];
      if (!Controller) return `controller${options.controller}未定义`;
    }

    const controller = new Controller(ctx);
    const MsgType = message.MsgType;
    const action = controller[`${MsgType}Action`];
    // eslint-disable-next-line no-return-await
    console.log("执行action", action);
    if (action) return await action(message);
    return "hello world";
  });
};
